package com.atguigu.gmall.payment.service.impl;



import com.alibaba.fastjson.JSONObject;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.atguigu.gmall.rebbit.constant.MqConst;
import com.atguigu.gmall.rebbit.service.RabbitService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @Author: 李旭
 * @Time: 15:10
 * @Description:
 *
 *   支付信息表
 *    CRUD
 */
@Service
public class PaymentInfoServiceImpl implements PaymentInfoService {


    @Autowired
    private PaymentInfoMapper paymentInfoMapper;
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private RabbitService rabbitService;
    //保存支付信息表
    @Override
    public PaymentInfo insert(Long orderId, PaymentType paymentType) {

        //幂等性问题
        //1:查询当前订单是否已经产生了支付信息
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>()
                .eq("order_id", orderId));
        if(null != paymentInfo){
            //2:查询修改就可以了
            paymentInfo.setPaymentType(paymentType.name());
            paymentInfo.setCreateTime(new Date());
            paymentInfoMapper.updateById(paymentInfo);
        }else{
            //2:添加
            paymentInfo = new PaymentInfo();
            //根据订单ID查询订单对象
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
            //交易号
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            //总金额
            paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
            //订单ID
            paymentInfo.setOrderId(orderInfo.getId());
            //付款方式
            paymentInfo.setPaymentType(paymentType.name());
            //为什么要支付这笔钱
            paymentInfo.setSubject(orderInfo.getTradeBody());
            //时间
            paymentInfo.setCreateTime(new Date());
            //支付状态
            paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());

            paymentInfoMapper.insert(paymentInfo);
        }
        return paymentInfo;
    }

    @Override
    public void paySuccess(Map<String, String> paramsMap) {
        //获取交易编号
        String out_trade_no = paramsMap.get("out_trade_no");

        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>()
                .eq("out_trade_no", out_trade_no));
        if(paymentInfo!=null){
            //判断是否时支付中
            if(PaymentStatus.UNPAID.name().equals(paymentInfo.getPaymentStatus())){
                //支付中改成已支付
                paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
                //添加支付宝获取的银行流水
                paymentInfo.setTradeNo(paramsMap.get("trade_no"));
                //回调时间
                String notify_time = paramsMap.get("notify_time");
                try {
                    paymentInfo.setCallbackTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                            .parse(notify_time));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //添加回调内容
                paymentInfo.setCallbackContent(JSONObject.toJSONString(paramsMap));
                paymentInfoMapper.updateById(paymentInfo);
                //发消息 更新订单，kucun
                rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,
                        MqConst.ROUTING_PAYMENT_PAY,paymentInfo.getOrderId());
            }
        }
    }
    @Autowired
    private AlipayService alipayService;

    @Override
    public void closePayment(Long orderId) {
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>().eq("order_id", orderId));
        //未支付的
        if(null != paymentInfo && paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.name())){
            //更新成关闭状态
            System.out.println("//更新成关闭状态");
            paymentInfo.setPaymentStatus(PaymentStatus.ClOSED.name());
            paymentInfoMapper.updateById(paymentInfo);
            //关闭支付宝
           // alipayService.closePay(paymentInfo);
        }
    }

}
